#include "piechart.h"
#include "ui_piechart.h"
#include <QAxObject>

Piechart::Piechart(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Piechart)
{
    ui->setupUi(this);
    setWindowTitle("柱状图");
    setWindowIcon(QIcon(":/image/P_mathematics.svg.png"));
    connect(ui->back,&QPushButton::clicked,[=](){
        emit back();
    });
    ui->title->setPlaceholderText("请输入表格标题");
    ui->holesize->setPlaceholderText("请输入孔洞大小（0~100%）");

    QRegExp rx("^-?(100|[1-9]?\\d(\\.\\d{1,4})?)$");//正则表达式，限制数字输入，限制在【0，100】之间
    QRegExpValidator *pReg = new QRegExpValidator(rx, this);
    ui->holesize->setValidator(pReg);

    //初始化表格
    QStringList PieChartHeader ;
    PieChartHeader << "输入单位" << "数据" ;
    QStringList PieChartIndex;
    PieChartIndex << "类别 1" << "类别 2" << "类别 3" << "类别 4";
    ui->tableWidget->setColumnCount(2);
    ui->tableWidget->setRowCount(5);
    for (int row = 0; row < PieChartIndex.size() ; row++)
        ui->tableWidget->setItem(row+1, 0, new QTableWidgetItem(PieChartIndex.at(row)));
    for (int col = 0; col < PieChartHeader.size() ; col++)
        ui->tableWidget->setItem(0, col, new QTableWidgetItem(PieChartHeader.at(col)));

    //美化表格
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setVisible(false);
    ui->tableWidget->verticalHeader()->setVisible(false);

    ui->tableWidget->setEditTriggers(QAbstractItemView::CurrentChanged);
    ui->tableWidget->setAlternatingRowColors(true);
}

Piechart::~Piechart()
{
    delete ui;
}

void Piechart::on_create_clicked()
{
    series = new QPieSeries();

    //冒泡排序，方便后面画图
    for(int row=1;row<ui->tableWidget->rowCount();row++)
    {
        for(int j=1;j<ui->tableWidget->rowCount()-row;j++)
        {
            if(ui->tableWidget->item(j, 1)->text().toDouble()>ui->tableWidget->item(j+1, 1)->text().toDouble())
            {
                QString a=ui->tableWidget->item(j, 1)->text();
                QString b=ui->tableWidget->item(j, 0)->text();
                ui->tableWidget->item(j, 0)->setText(ui->tableWidget->item(j+1, 0)->text());
                ui->tableWidget->item(j, 1)->setText(ui->tableWidget->item(j+1, 1)->text());
                ui->tableWidget->item(j+1, 0)->setText(b);
                ui->tableWidget->item(j+1, 1)->setText(a);
            }
        }
    }

    //读取名字和数据
    for (int row = 1; row < ui->tableWidget->rowCount(); row++)
        series->append(ui->tableWidget->item(row, 0)->text(), ui->tableWidget->item(row, 1)->text().toDouble());

    if (ui->ishole->isChecked())
    {
        if (ui->holesize->text().isEmpty())
        {
            QMessageBox::warning(this, "警告", "请输入孔洞大小");
            return;
        }
        else
            series->setHoleSize(7*(ui->holesize->text().toDouble())/1000);//设置孔洞
    }
    else
        series->setHoleSize(0);//设置无孔洞

    series->setLabelsVisible(true);

    qreal factor=0.15;
    pieSlice=new QPieSlice();
    for (int i = 0; i < ui->tableWidget->rowCount()-1; i++)
    {
        pieSlice = series->slices().at(i); //获取分块
        pieSlice->setLabel(pieSlice->label() + QString(" %1").arg(pieSlice->value())+QString(ui->tableWidget->item(0,0)->text())+QString(", %2%").arg(pieSlice->percentage()*100));
        //信号与槽函数关联，鼠标落在某个分块上时，此分块弹出
        connect(pieSlice, SIGNAL(hovered(bool)), this, SLOT(on_PieSliceHighlight(bool)));
        pieSlice->setLabelFont(QFont("微软雅黑"));

        //避免标签重叠
        if (pieSlice->percentage() < 0.1) {
            pieSlice->setLabelArmLengthFactor(factor);//设置折线长度
            factor += 0.07;  //若还有小数据，则继续加长，不需要加长的数据由系统设置默认长度
            //调整起始、结束角度. 目的是将数值较小的区域调整到右下角
            if (series->pieStartAngle() < 120) {
                series->setPieStartAngle(120);
                series->setPieEndAngle(360 + 120);
            }
        }
    }

    QChart *chart = new QChart();
    chart->addSeries(series);
    chart->setTitle(ui->title->text());
    chart->setTitleFont(QFont("微软雅黑"));
    chart->setAnimationOptions(QChart::SeriesAnimations);
    chart->legend()->setAlignment(Qt::AlignRight);

    QChartView *chartView = new QChartView(chart);
    chartView->setRenderHint(QPainter::Antialiasing);
    chartView->setWindowTitle("饼图");
    chartView->setWindowIcon(QIcon(":/image/P_mathematics.svg.png"));
    chartView->resize(1200, 800);
    chartView->show();
}

void Piechart::on_add_clicked()
{
    int count = ui->tableWidget->rowCount();
    ui->tableWidget->setRowCount(count + 1);
    ui->tableWidget->setItem(count,0,new QTableWidgetItem("类别 "+QString::number(count)));
}

void Piechart::on_deleteone_clicked()
{
    int count = ui->tableWidget->rowCount();
    if (count > 3)
        ui->tableWidget->setRowCount(count - 1);
    else QMessageBox::warning(this, "警告", "至少保留两行");
}

void Piechart::on_PieSliceHighlight(bool show)
{
    //鼠标移入、移出时触发hovered()信号，动态设置setExploded()效果
    pieSlice = (QPieSlice *)sender();
    pieSlice->setExploded(show);
}


void Piechart::on_clear_clicked()
{
    int rowcount=ui->tableWidget->rowCount();
    for(int i=1;i<rowcount;i++){
        QTableWidgetItem* item = ui->tableWidget->item(i, 1);
        if(item==nullptr)
            ui->tableWidget->setItem(i, 1, new QTableWidgetItem(""));
        else
            ui->tableWidget->item(i,1)->setText("");
        }
    ui->tableWidget->item(0,0)->setText("输入单位");
    ui->tableWidget->item(1,0)->setText("数据");
    for(int i=1;i<rowcount;i++)
        ui->tableWidget->item(i,0)->setText("类别 " + QString::number(i));
}

void Piechart::on_pushButton_clicked()
{
    QString fileName=QFileDialog::getOpenFileName(this,"读取","C:\\Users","(*.xlsx)");
    if(fileName.isEmpty())
        return;
    fileName=QDir::toNativeSeparators(fileName);

    QAxObject* excel = new QAxObject("Excel.Application", this);
    QAxObject* workbooks = excel->querySubObject("Workbooks");
    QAxObject* workbook = workbooks->querySubObject("Open(const QString&)", fileName);
    QAxObject* sheets = workbook->querySubObject("Sheets");
    QAxObject* sheet = sheets->querySubObject("Item(int)", 1); // 第一个工作表
    QAxObject* usedRange = sheet->querySubObject("UsedRange");
    QAxObject* rows = usedRange->querySubObject("Rows");

    int rowCount = rows->property("Count").toInt();

    ui->tableWidget->setRowCount(rowCount+1);

    for(int i=0;i<ui->tableWidget->rowCount();i++)
    {
        QTableWidgetItem* item = ui->tableWidget->item(i, 1);
        if(item==nullptr)
            ui->tableWidget->setItem(i, 1, new QTableWidgetItem(""));
    }

    for (int row = 1; row <= rowCount; ++row)
    {
        QAxObject* cell = sheet->querySubObject("Cells(int,int)", row, 1);
        QString value = cell->property("Value").toString();
        ui->tableWidget->item(row, 1)->setText(value);
    }

    workbook->dynamicCall("Close()");
    excel->dynamicCall("Quit()");
}
